<template>
  <div class="project-home common-container">
    <header-title title="项目">
      <template #right>
        <el-button class="btn-add" type="primary" size="small" @click="addInit">新项目</el-button>
      </template>
    </header-title>
    <div class="project-home__content">
      <div class="filter-wrap">
        <div class="total">
          <span
            class="cup total-text"
            :class="{ 'is-active': queryForm.focus === numObj.all }"
            @click="clickCount(numObj.all)"
            >全部</span
          >
          <span class="num">{{ state.projectCount }}</span>

          <span
            style="margin-left: 20px"
            class="cup total-text"
            :class="{ 'is-active': queryForm.focus === numObj.focus }"
            @click="clickCount(numObj.focus)"
            >关注</span
          >
          <span class="num">{{ state.focusProjectCount }}</span>
        </div>
        <div class="filter-right">
          <el-form :inline="true" :model="queryForm">
            <el-form-item label>
              <select-form
                v-model="queryForm.sort"
                :multiple="false"
                :options="typeOptions"
                placeholder="选择项目类型查询"
                @change="search"
              />
            </el-form-item>
            <el-form-item label>
              <!-- <el-input v-model="queryForm.name" placeholder="输入项目名称精确查询">
                <template #append>
                  <el-button @click="search">
                    <el-icon>
                      <Search />
                    </el-icon>
                  </el-button>
                </template>
              </el-input>-->
              <search-input
                v-model="queryForm.name"
                placeholder="输入项目名称精确查询"
                @search="search"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div v-loading="tableLoading" class="project-list">
        <template v-if="tableData.length > 0">
          <div
            v-for="(item, index) in tableData"
            :key="index"
            class="project-item"
            @click="goProject(item.pid, item.name)"
          >
            <div class="project-item__top">
              <div class="left">
                <el-avatar
                  style="background: transparent"
                  :size="50"
                  shape="square"
                  cross-origin
                  :src="formatIcon(item.icon)"
                />
                <span class="cup project-name m-r-5">{{ item.name }}</span>
              </div>
              <div class="right">
                <span>
                  <svg-icon icon-class="subject-pro" class="desc-icon" />
                  <span>受试者：</span>
                  <span>{{ item.subject }}</span>
                </span>
                <span>
                  <svg-icon icon-class="visit-pro" class="desc-icon" />
                  <span>访视：</span>
                  <span>{{ item.visit }}</span>
                </span>
                <span>
                  <svg-icon icon-class="issue-pro" class="desc-icon" />
                  <span>质疑：</span>
                  <span>{{ item.issues }}</span>
                </span>
              </div>
            </div>
            <div class="project-item__bottom">
              <div class="left">
                <div>
                  <span>项目负责人：</span>
                  <span>{{ item.pm }}</span>
                </div>
              </div>

              <div class="right">
                <span>创建时间：{{ item.createTime }}</span>
              </div>
            </div>
            <el-tag
              class="focus-icon"
              v-if="getProjectStatus(item.enable)?.value"
              :style="{
                color: getProjectStatus(item.enable)?.color,
                background: getProjectStatus(item.enable)?.background,
              }"
              >{{ getProjectStatus(item.enable)?.value }}</el-tag
            >
            <!-- <span class="focus-icon">
              <el-tooltip :content="item.focus ? '取消关注' : '关注'">
                <el-icon
                  v-if="item.focus"
                  :size="28"
                  style="color: #ffd400fa"
                  @click="unFoucs(item.pid, $event)"
                >
                  <star-filled />
                </el-icon>

                <el-icon v-else :size="24" @click="foucs(item.pid, $event)">
                  <star />
                </el-icon>
              </el-tooltip>
            </span> -->
          </div>
        </template>
        <empty v-else />
      </div>
      <pagination
        v-model:currentPage="pageObj.pageNum"
        v-model:pageSize="pageObj.pageSize"
        :total="pageObj.total"
        @pagination="search"
      />
    </div>

    <!-- 新项目对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新项目"
      width="960px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-steps :active="stepIndex" align-center finish-status="success">
        <el-step title="项目信息" />
        <el-step title="项目详情" />
        <el-step title="完成" />
      </el-steps>
      <add-form
        ref="addFormRef"
        class="add-form-wrap"
        :step-index="stepIndex"
        :dict-data="dictStore.dictData"
        :dict-id-maps="dictIdMaps"
      />
      <template #footer>
        <el-row :justify="stepIndex === 0 ? 'end' : 'space-between'" class="dialog-footer">
          <!-- <el-button @click="dialogVisible = false">取消</el-button> -->
          <el-button v-if="stepIndex !== 0 && stepIndex !== 2" type="primary" @click="stepIndex--"
            >上一步</el-button
          >
          <el-button v-if="stepIndex === 0" type="primary" @click="stepIndex++">下一步</el-button>
          <el-button v-if="stepIndex === 1" v-loading="saveLoading" type="primary" @click="submit"
            >创建</el-button
          >
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'

import SearchInput from '@/components/CommonSearch/SearchInput/index.vue'
import Empty from '@/components/EmptyBlock/index.vue'
import SelectForm from '@/components/Form/Select.vue'
import HeaderTitle from '@/components/HeaderTitle/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import AddForm from './AddForm.vue'

import profilePhoto from '@/assets/profile-photo.jpg'

import { getOrgClsList, orgType } from '@/api/common'
import ProjectApi from '@/api/project'
import { useDict } from '@/api/uses'

import { useDictStore } from '@/store/dict'
import { useProjectStore } from '@/store/project'
import { useUserStore } from '@/store/user'

import { formatUrl } from '@/utils/common/formatUrl'
import { hexToRgb } from '@/utils'

import { commonHandle } from '@/views/mixins/common'
import IBaseObj from '#/index'
const { dictIdMaps } = useDict()
const { getDictData } = useDictStore()
const dictStore = useDictStore()

const stepIndex = ref(0)

const formatIcon = (icon: string) => {
  const format = icon ? formatUrl(icon) : profilePhoto

  return format
}

const { uid } = useUserStore().userInfo
const { getMenu } = useProjectStore()

const { handleSearch, state: tableState } = commonHandle()
const { tableData, tableLoading, pageObj }: IBaseObj = toRefs(tableState)

const numObj = {
  all: '',
  focus: true,
}

const state: IBaseObj = reactive({
  queryForm: {
    sort: '',
    name: '',
    uid,
    focus: '',
  },
  typeOptions: [],
  stagingOptions: [],
  fieldOptions: [],
  croOptions: [],
  biddersOptions: [], // 申办方
  researchOptions: [], // 研究单位
  addForm: {
    name: '',
    license: '',
    sort: '',
    staging: [],
    bidders: [],
    cro: [],
    research: [],
    field: [],
    depict: '',
  },
  dialogVisible: false,
  saveLoading: false,
  projectCount: 0,
  focusProjectCount: 0,
})

const { queryForm, typeOptions, addForm, dialogVisible, saveLoading } = toRefs(state)

const getProjectStatus = computed(() => {
  return (status: string | number) => {
    const obj = dictStore.dictData[dictIdMaps.projectStatus]?.find(
      (v: IBaseObj) => v.code === status
    )
    const color = hexToRgb(obj?.color || '', 0.2)

    return {
      ...obj,
      background: color.rgba,
    }
  }
})

const search = () => {
  handleSearch(ProjectApi.getProjectByPage, state.queryForm)
}

const getProjectCount = async () => {
  const ret = await ProjectApi.getProjectCount(uid)
  state.projectCount = ret || 0
}

const getFocusProjectCount = async () => {
  const ret = await ProjectApi.getFocusProjectCount(uid)
  state.focusProjectCount = ret || 0
}

const clickCount = (val: string | boolean) => {
  state.queryForm.focus = val
  search()
}

const addInit = () => {
  state.dialogVisible = true
}

const getOrgCls = async () => {
  const ret = await getOrgClsList()
  const data = ret.data
  state.croOptions = data && data[orgType.cro]
  state.biddersOptions = data && data[orgType.sbdw]
  state.researchOptions = data && data[orgType.yjdw]
}

const router = useRouter()
const setProjectRoute = async (pid: string, name: string) => {
  const ret: any = await getMenu({
    uid,
    pid,
  })

  const routes = ret && ret.filter((v: any) => v.path !== '/project/home')

  let firstPath = ''

  console.log('ttt', routes)

  const getFirstRoute = (routes: any) => {
    console.log('ttt', routes)

    for (let i = 0; i < 1; i++) {
      if (!routes[i].children || routes[i].children.length === 0) {
        firstPath = `${routes[i].path}?pid=${pid}&pname=${name}`
        return
      }
      getFirstRoute(routes[i].children)
    }
  }

  getFirstRoute(routes)

  firstPath && router.push(firstPath)
}
const goProject = (id: string, name: string) => {
  setProjectRoute(id, name)
  // router.push(`/project/visit?pid=${id}&pname=${name}`)
}

const addFormRef = ref()

const closeDialog = () => {
  addFormRef.value.clear()
}

const submit = async () => {
  const valid = await addFormRef.value.valid()

  if (valid) {
    saveLoading.value = true
    try {
      const ret = await ProjectApi.createProject({
        ...addFormRef.value.form,
      })
      console.log('r', ret)
      if (ret) {
        ElMessage({
          type: 'success',
          message: '添加成功！',
        })
        search()
      }
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const foucs = async (pid: number, e: Event) => {
  e.stopPropagation()
  const ret = await ProjectApi.foucs(pid, uid)
  if (ret.data) {
    search()
    getFocusProjectCount()
  }
}

const unFoucs = async (pid: number, e: Event) => {
  e.stopPropagation()
  const ret = await ProjectApi.unfoucs(pid, uid)
  if (ret.data) {
    search()
    getFocusProjectCount()
  }
}

const init = () => {
  search()
  getDictData()

  // getOrgCls()
  // getProjectCount()
  // getFocusProjectCount()
}
init()
</script>

<style lang="scss" scoped>
.project-home {
  width: 100%;

  &__title {
    height: 60px;
    padding-left: 30px;
    font-size: 22px;
    line-height: 60px;
    color: var(--color-1);
  }

  &__content {
    display: flex;
    width: 960px;
    height: calc(100% - 60px);
    margin: auto;
    flex-direction: column;
  }

  .total {
    padding: 20px 0;
    font-size: 16px;

    &-text {
      font-weight: 600;
    }

    .is-active {
      color: var(--color-primary);
    }

    .num {
      margin-left: 18px;
      color: var(--color-2);
    }
  }
}

.project {
  &-name {
    margin-left: 10px;
    font-size: 18px;
    font-weight: 600;
  }

  &-list {
    flex: 1;
    overflow: auto;
    @include scroll-bar;
  }

  &-item {
    position: relative;
    font-size: 16px;
    cursor: pointer;
    border: 1px solid var(--table-border);
    border-radius: 6px;

    & + & {
      margin-top: 20px;
    }

    &__top {
      display: flex;
      height: 82px;
      background: #eaf2ff;
      border-bottom: 1px solid var(--table-border);
      border-radius: 6px 6px 0 0;
      align-items: center;

      .block {
        display: inline-block;
        width: 30px;
        height: 30px;
        margin-right: 10px;
        background: #7d5290;
      }

      .left {
        display: flex;
        padding-left: 20px;
        flex: 1;
        align-items: center;
      }

      .right {
        display: flex;
        width: 40%;
        padding-right: 40px;
        align-items: center;

        & > span {
          display: flex;
          margin-left: 15px;
          align-items: center;

          &:first-child {
            margin-left: 0;
          }
        }
      }
    }

    &__bottom {
      display: flex;
      height: 82px;
      background: #fff;
      border-radius: 0 0 6px 6px;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        padding-left: 60px;

        & > div {
          margin-right: 10px;
        }
      }

      .right {
        padding-right: 80px;
        font-size: 14px;
        color: var(--color-2);
      }
    }
  }
}

.desc-icon {
  margin-right: 5px;
  font-size: 20px;
  color: var(--mainnav-color);
}

.focus-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

.filter-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-right {
  display: flex;
  align-items: center;

  :deep() {
    .el-input {
      font-size: 13px;
    }

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.add-form-wrap {
  margin-top: 20px;
}
</style>
